package com.weixin.api.rest;

import com.weixin.common.ResponseResult;
import com.weixin.domain.sm.Employee;
import com.weixin.request.RegisterCustomerRequest;
import com.weixin.response.LoginResponse;
import com.weixin.server.sm.EmployeeService;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author lc
 * @email 389125111@qq.com
 * @create 2018-03-12 14:19
 */
@RestController
@RequestMapping("weixinRest")
@Api(description = "测试接口相关")
public class WeiXinRest {
    Logger logger = LoggerFactory.getLogger(WeiXinRest.class);

    @Autowired
    private EmployeeService employeeService;

    @ApiOperation(value = "登录相关", notes = "注意事项")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ResponseResult<LoginResponse> login(@ApiParam(required = true, name = "username", value = "用户名") @RequestParam(required = true) String username,
                                               @ApiParam(required = true, name = "password", value = "密码") @RequestParam(required = true) String password,
                                               @ApiParam(required = false, name = "rememberMe", value = "记住我") @RequestParam(required = true, defaultValue = "false") boolean rememberMe) {
        ResponseResult result = new ResponseResult<>();

        /**验证账号密码*/
        LoginResponse response = employeeService.findByUsername(username);
        if (null == response) {
            result = ResponseResult.success_data_null();
            return result;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(response.getId().toString(), password);
        token.setRememberMe(rememberMe);
        subject.login(token);
        Session session = subject.getSession();
        String sessionId = String.valueOf(session.getId());
        session.setAttribute("login_staff_id", response.getId());
        result.setData(sessionId);
        return result;
    }

    @ApiOperation(value = "注册", notes = "返回data没有内容")
    @RequestMapping(value = "/registerCustomer", method = RequestMethod.POST)
    public ResponseResult registerCustomer(@RequestBody RegisterCustomerRequest request) {
        ResponseResult result;
        if (null == request || null == request.getUsername() || null == request.getPassword()) {
            result = ResponseResult.param_error();
        } else {
            employeeService.registerCustomer(request);
            result = ResponseResult.success(null);
        }
        return result;
    }


}
